<template>
    <div class="app-container">
        <el-form
            ref="queryParamsRef"
            :inline="true"
            :model="queryParams"
            label-width="auto"
            label-position="left"
        >
            <el-form-item label="用警单位：" prop="unitId">
                <DepartmentCascader v-model="queryParams.unitId" @change="getTableData"/>
            </el-form-item>
            <el-form-item label="含下级：">
                <el-switch v-model="queryParams.selChildren" @change="getTableData"/>
            </el-form-item>
            <el-form-item label="执勤日期：">
                <el-date-picker
                    v-model="searchTime"
                    type="daterange"
                    unlink-panels
                    range-separator="-"
                    start-placeholder="开始时间"
                    end-placeholder="截止时间"
                    value-format="YYYY-MM-DD"
                    @change="changeDateTimerHandle"
                />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="getTableData">
                    <el-icon class="me-1">
                        <Search/>
                    </el-icon>
                    查询
                </el-button>
            </el-form-item>
            <el-form-item>
                <el-button @click="resetQueryParamsHandle(queryParamsRef)">
                    <el-icon class="me-1">
                        <Refresh/>
                    </el-icon>
                    重置
                </el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="warning" @click="exportHandleXlsx('单位执法档案统计表')">
                    <el-icon class="me-1">
                        <Download/>
                    </el-icon>
                    导出
                </el-button>
            </el-form-item>
        </el-form>

        <el-divider class="mt-0"/>

        <el-table
            :data="tableData"
            v-loading="loading"
            border
            stripe
            :row-style="tableRowStyle"
            show-summary
            :summary-method="getSummaryData"
        >
            <el-table-column
                v-for="column in column"
                :label="column.label"
                :prop="column.id"
                :key="column.id"
                align="center"
            >
                <template v-if="column.children.length >= 1">
                    <el-table-column
                        v-for="child in column.children"
                        :key="child.id"
                        :label="child.label"
                        :prop="child.id"
                        align="center"
                    />
                </template>
            </el-table-column>
            <!--            <el-table-column label="合计" align="center" prop="rowTotal"/>-->
            <!--            <el-table-column-->
            <!--                v-for="c in column"-->
            <!--                :key="c.key"-->
            <!--                :label="c.label"-->
            <!--                :prop="c.key"-->
            <!--                align="center"-->
            <!--            />-->
            <el-table-column label="合计" align="center">
                <template #default="scope">
                    {{ calculateTotal(scope.row, totalColumnKey) }}
                </template>
            </el-table-column>
        </el-table>

    </div>
</template>

<script setup>
import {Download, Refresh, Search} from "@element-plus/icons-vue";
import {useTemplateRef} from "vue";
import DepartmentCascader from "@/components/DepartmentCascader/DepartmentCascader.vue";
import {getUnitRegisterTableData, getUnitRegisterTableHead} from "@/api/StatisticAnalysis/UnitRegistTotal.js";
import {calculateTotal} from "@/utils/utils.js";
import usePermissionStore from "@/store/modules/permission.js";
import {exportHandleXlsx} from "@/utils/export.js";

const permissionStore = usePermissionStore()
const searchTime = ref([]);
const queryParams = ref({
    // 部门 ID
    unitId: '',
    // 是否包含下级
    selChildren: false,
    params: {
        beginTime: '',
        endTime: ''
    }
});
const queryParamsRef = useTemplateRef('queryParamsRef')

onMounted(() => {
    getTableHead().then(() => {
        getTableData()
    })
});
// 斑马纹样式函数
const tableRowStyle = ({ row, rowIndex }) => {
    if (rowIndex % 2 === 0) {
        return { backgroundColor: '#e6ecff' }; // 偶数行背景色
    }
    return {}; // 奇数行默认透明
}
const loading = ref(false);
// 头部名称
const column = ref([
    {key: 'unitName', label: '单位', width: 100},
]);
// table 数据
const tableData = ref([]);
// 需要统计的行key
const totalColumnKey = ref([]);

// 获取头部
const getTableHead = async () => {
    const res = await getUnitRegisterTableHead();
    // totalColumnKey.value = Object.keys(res.data)
    // Object.keys(res.data).map(item => column.value.push({
    //     key: item,
    //     label: res.data[item],
    //     width: res.data[item].length * 25
    // }))

    column.value = [
        ...[
            {id: 'unitName', label: '单位', children: []},
        ],
        ...res.data
    ]
}
// 改变时间
const changeDateTimerHandle = (date) => {
    if (date) {
        queryParams.value = {
            ...queryParams.value,
            params: {
                beginTime: date[0],
                endTime: date[1]
            }
        }
    } else {
        queryParams.value = {
            ...queryParams.value,
            params: {
                beginTime: '',
                endTime: ''
            }
        }
    }

    getTableData()
}

// 获取数据源
const getTableData = async () => {
    loading.value = true;
    const res = await getUnitRegisterTableData(queryParams.value);
    tableData.value = res.data;
    loading.value = false;
}

// 获取总合数据
const getSummaryData = ({columns, data}) => {

    const row = [];
    columns.forEach((column, index) => {

        if (column.rawColumnKey === 'unitName') {
            row[index] = '合计';
            return '';
        }

        if (column.rawColumnKey === 'userName') {
            row[index] = '';
            return '';
        }

        if (row.label === '合计') {
            return '';
        }

        const values = data.map((item) => Number(item[column.property]))

        if (!values.every((value) => Number.isNaN(value))) {
            row[index] = values.reduce((prev, curr) => {
                return prev + curr;
            });
        }
    });

    row.push(calculateTotal(row, totalColumnKey.value.map(item => Number(item))))

    return row;
}

// 重置搜索
const resetQueryParamsHandle = async (elForm) => {
    if (!elForm) return
    elForm.resetFields()
    searchTime.value = []
    queryParams.value.params.beginTime = '';
    queryParams.value.params.endTime = '';
    queryParams.value.selChildren = false;
    await getTableData()
}
</script>

<style lang="scss" scoped>
/* 保留斑马纹的同时添加悬停效果 */
:deep().el-table--striped .el-table__body tr.el-table__row--striped:hover td {
  background-color: #a5b8f4; /* 悬停时的红色 */
}

:deep().el-table__body tr:hover td {
  background-color: #a5b8f4; /* 悬停时的红色 */
}

</style>